# -*- coding: utf-8 -*-
from asyncio.log import logger
from django.utils import timezone
from django.db import DatabaseError, transaction
from django.http import JsonResponse
from django.shortcuts import render
from .models import *
# Create your views here.


def home(request):
    """
    首页
    """
    return render(request, 'index.html')

# 新增任务及编辑，修改
def save_list_info(request):
    """
    新增任务
    """
    # try: 
    if request.method == 'GET':

        list_title = request.GET.get('list_title')
        print('list_title',list_title)
        list_content = request.GET.get('list_content')
        list_note = request.GET.get('list_note')
        plan_completion_time = request.GET.get('plan_completion_time')
        print('plan_time', plan_completion_time)
        kwargs = {
            "list_title": list_title,
            "list_content": list_content,
            "list_note": list_note,
            "plan_completion_time": plan_completion_time,
        }
        list_id = request.GET.get("id", None)
        # 编辑任务信息
        if list_id:
            try:
                List.objects.filter(id=list_id).update(**kwargs)
                return JsonResponse({"result": True, "code": 200, "message": "修改成功!"})
            except Exception:
                return JsonResponse({"result": False, "code": 101, "message": "修改任务失败！"})

        try:
            List.objects.create(**kwargs)
        except Exception as err:
            print(err)
            return JsonResponse({"result": False, "code": 101, "message": "保存任务失败！"})

        return JsonResponse({"result": True, "code": 200, "message": "任务创建成功，请尽快完成!"})

    

# 新增模板及编辑，修改
def save_template_info(request):
    """
    新增模板
    """
    if request.method == 'GET':
        
        template_title = request.GET.get('template_title')
        template_content = request.GET.get('template_content')
        template_note = request.GET.get('template_note')
        visible_range = request.GET.get('visible_range')
        print('template_titlel', template_title)
        print('visible_range', visible_range)
        template_create_person = request.user.username
        kwargs = {
            "template_title": template_title,
            "template_content": template_content,
            "template_note": template_note,
            "visible_range": int(visible_range),
            "template_create_person": template_create_person
        }
        template_id = request.GET.get("id", None)

        # 编辑模板信息
        if template_id:
            try:
                Template.objects.filter(id=template_id).update(**kwargs)
                return JsonResponse({"result": True, "code": 200, "message": "修改成功!"})
            except Exception:
                return JsonResponse({"result": False, "code": 101, "message": "修改模板失败！"})

        
        # 添加模板数据
        try:
            Template.objects.create(**kwargs)
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "创建模板失败！"})

        return JsonResponse({"result": True, "code": 200, "message": "模板创建成功!"})


# 获取任务列表
def get_list(request):
    """
    获取任务列表数据
    """
    if request.method == "POST":
        list = List.objects.all()

        result_data = []
        for item in list:
            result_data.append(
                {
                    "id": item.id,
                    "list_title": item.list_title,
                    "list_content": item.list_content,
                    "list_status": item.get_list_status_display(),
                    "list_note": item.list_note,
                    "plan_completion_time": item.plan_completion_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "actual_completion_time": item.actual_completion_time,
                    "create_time": item.create_time.strftime("%Y-%m-%d %H:%M:%S")
                }
            )
        return JsonResponse(
            {
                "result": True, "code": 200,
                "data": result_data
            }
        )

# 获取模板列表及查询接口
def get_template_list(request):
    """
    获取模板列表数据
    """
    if request.method == 'POST':
        templates = Template.objects.all()
        result_data = []
        for item in templates:
            result_data.append(
                {
                    "id": item.id,
                    "template_title": item.template_title,
                    "template_content": item.template_content,
                    "template_note": item.template_note,
                    "visible_range": item.visible_range,
                    "template_update_time": item.template_update_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "template_create_time": item.template_create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "template_create_person": item.template_create_person
                }
            )
        return JsonResponse(
            {
                "result": True, "code": 200,
                "data": result_data
            }
        )
        # 查询
    if request.method == 'GET':
        template_title = request.GET.get("search_template_name")
        if template_title is None:
            return JsonResponse(
                {"result": False, "code": 400, "message": "该模板不存在", "data": {}}
            )

        try:
            templates = list(Template.objects.filter(template_title=template_title).values())
        except DatabaseError as e:
            logger.exception(e)
            return JsonResponse(
                {"result": True, "code": 500, "message": "查询失败(请检查日志)", "date": {}}
            )
        return JsonResponse(
            {
                "result": True,
                "code": 200,
                "message": "查询成功",
                "data": templates,
            }
        )

def complete_list(request):
    if request.method == 'GET':
        try:
            with transaction.atomic():
                list_id = request.GET.get("list_id")
                list = List.objects.get(id = int(list_id))
                list.actual_completion_time = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
                list.list_status = ListStatus.COMPLETED
                list.save()
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "完成任务失败"})
        return JsonResponse(
            {
                "result": True, "code": 200,
                "message": "该任务已完成"
            }
        )
def refuse_list(request):
    if request.method == 'GET':
        try:
            with transaction.atomic():
                list_id = request.GET.get("list_id")
                list = List.objects.get(id = int(list_id))
                list.actual_completion_time = None
                list.list_status = ListStatus.REFUSED
                list.save()
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "拒接任务失败"})
        return JsonResponse(
            {
                "result": True, "code": 200,
                "message": "该任务已拒绝"
            }
        )
def cancle_list_status(request):
    if request.method == 'GET':
        try:
            with transaction.atomic():
                list_id = request.GET.get("list_id")
                list = List.objects.get(id = int(list_id))
                list.list_status = ListStatus.PENDING
                list.actual_completion_time = None
                list.save()
        except Exception as error:
            print('error', error)
            return JsonResponse({"result": False, "code": 101, "message": "取消失败"})
        return JsonResponse(
            {
                "result": True, "code": 200,
                "message": "取消成功"
            }
        )
# 删除任务接口
def delete_list_info(request):
    """
    删除任务数据
    """
    if request.method == 'GET':
        list_id = request.GET.get("list_id")
        try:
            with transaction.atomic():
                list = List.objects.get(id=int(list_id))
                list.delete()
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "删除任务失败！"})
        return JsonResponse(
            {
                "result": True, "code": 200,
                "message": "删除成功！"
            }
        )

# 删除模板接口
def delete_template_info(request):
    """
    删除模板数据
    """
    if request.method == 'GET':
        template_id = request.GET.get("template_id")
        try:
            with transaction.atomic():
                template = Template.objects.get(id=int(template_id))
                template.delete()
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "删除模板失败！"})
        return JsonResponse(
            {
                "result": True, "code": 200,
                "message": "删除成功！"
            }
        )
